/*
 *  (C) Copyright 2008 Insula T.I. Ltda.
 *
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.orm.command;

import java.util.List;

import org.hibernate.NonUniqueObjectException;
import org.openinsula.vulcano.core.annotation.RequiresDependencyInjection;
import org.openinsula.vulcano.core.command.Command;
import org.openinsula.vulcano.orm.InitializingCallback;
import org.springframework.orm.hibernate3.HibernateInterceptor;
import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;

/**
 * {@link Command} decorator used to insulate bean initializing logic from query
 * logic. This decorator operates on a {@link Command} that returns a
 * {@link List}.
 *
 * <p>
 * Usually it is recommended to use {@link InitializingCommandWrapper} or
 * {@link IterableInitializingCommandWrapper} with an
 * {@link InitializingCallback} rather than the {@link HibernateInterceptor} or
 * {@link OpenSessionInViewFilter}. This approach tends to reduce the amount of
 * {@link NonUniqueObjectException}.
 *
 * @author yanaga
 *
 * @param <T> The {@link Command} return type.
 * @since 1.1
 * @see Command
 * @see InitializingCallback
 * @see InitializingCommandWrapper
 */
public class IterableInitializingCommandWrapper<T> implements Command<List<T>> {

	private static final long serialVersionUID = 1L;

	@RequiresDependencyInjection
	private final Command<List<T>> wrappedCommand;

	private final InitializingCallback<T> initializingCallback;

	public IterableInitializingCommandWrapper(final Command<List<T>> wrappedCommand,
			final InitializingCallback<T> initializingCallback) {
		this.wrappedCommand = wrappedCommand;
		this.initializingCallback = initializingCallback;
	}

	@Override
	public List<T> execute() {
		List<T> result = wrappedCommand.execute();

		if (result != null) {
			for (T obj : result) {
				initializingCallback.init(obj);
			}
		}

		return result;
	}

}
